import React, {useEffect, useState} from 'react';
import {Button, Form, Input, message, Modal, Space, Switch, Table} from 'antd';
import {DeleteOutlined, EditOutlined, PlusOutlined} from '@ant-design/icons';
import type {ColumnsType} from 'antd/es/table';
import {createLanguage, deleteLanguage, getLanguages, updateLanguage, updateLanguageEnable} from '../../api/language';


interface Language {
  id: string;
  name: string;
  description: string;
  enable: boolean;
}

const AddLanguageForm: React.FC<{ form: any; onFinish: (values: any) => void }> = ({ form, onFinish }) => (
  <Form form={form} layout="vertical" onFinish={onFinish}>
    <Form.Item
      name="name"
      label="语言名称"
      rules={[{ required: true, message: '请输入语言名称' }]}
      tooltip="例如：日本語"
    >
      <Input placeholder="请输入语言名称" />
    </Form.Item>
    <Form.Item
      name="code"
      label="语言代码"
      rules={[{ required: true, message: '请输入语言代码' }, { pattern: /^[a-z]{2}-[A-Z]{2}$/, message: '语言代码格式应为 xx-XX，例如：ja-JP' }]}
      tooltip="语言代码格式应为 xx-XX，例如：ja-JP"
    >
      <Input placeholder="请输入语言代码，例如：ja-JP" />
    </Form.Item>
    <Form.Item
      name="description"
      label="描述"
      tooltip="语言的描述信息"
    >
      <Input.TextArea placeholder="请输入语言描述" />
    </Form.Item>
    <Form.Item
      name="enable"
      label="状态"
      valuePropName="checked"
      initialValue={true} // 确保默认值为 true
    >
      <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked />
    </Form.Item>
  </Form>
);

const EditLanguageForm: React.FC<{ form: any; onFinish: (values: any) => void; initialValues: Language }> = ({ form, onFinish, initialValues }) => (
  <Form form={form} layout="vertical" onFinish={onFinish} initialValues={initialValues}>
    <Form.Item
      name="name"
      label="语言名称"
      rules={[{ required: true, message: '请输入语言名称' }]}
      tooltip="例如：日本語"
    >
      <Input placeholder="请输入语言名称" />
    </Form.Item>
    <Form.Item
      name="description"
      label="描述"
      tooltip="语言的描述信息"
    >
      <Input.TextArea placeholder="请输入语言描述" />
    </Form.Item>
    <Form.Item
      name="enable"
      label="状态"
      valuePropName="checked"
    >
      <Switch checkedChildren="启用" unCheckedChildren="禁用" />
    </Form.Item>
  </Form>
);

const LanguageList: React.FC = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<string | null>(null);
  const [languages, setLanguages] = useState<Language[]>([]);
  const [pagination, setPagination] = useState({ page: 1, pageSize: 10 });
  const [searchText, setSearchText] = useState(''); // 新增搜索框状态

  useEffect(() => {
    const fetchLanguages = async () => {
      try {
        const data = await getLanguages(pagination.page, pagination.pageSize);
        setLanguages(data);
      } catch (error) {
        message.error('获取语言列表失败');
      }
    };

    fetchLanguages();
  }, [pagination]);

  // 新增搜索框的过滤逻辑
  const filteredLanguages = languages.filter((lang) =>
    lang.name.toLowerCase().includes(searchText.toLowerCase()) ||
    lang.description?.toLowerCase().includes(searchText.toLowerCase())
  );

  const columns: ColumnsType<Language> = [
    {
      title: '语言名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '语言代码',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '状态',
      key: 'status',
      render: (_, record) => (
        <Switch
          checked={record.enable}
          onChange={(checked) => handleToggleEnable(record.id, checked)}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingId(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (record: Language) => {
    setEditingId(record.id);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个语言吗？',
      onOk: async () => {
        try {
          // 调用API删除语言
          await deleteLanguage(id);

          // 更新本地状态
          setLanguages(languages.filter(item => item.id !== id));
          message.success('删除成功');
        } catch (error) {
          console.error('删除语言失败:', error);
          message.error('删除失败，请重试');
        }
      },
    });
  };

  const handleToggleEnable = async (id: string, enabled: boolean) => {
    try {
      // 调用API更新语言启用状态
      await updateLanguageEnable(id, enabled);

      // 更新本地状态
      setLanguages(languages.map(item =>
        item.id === id ? { ...item, enable: enabled } : item
      ));
      message.success(`语言已 ${enabled ? '启用' : '禁用'}`);
    } catch (error) {
      console.error('更新语言状态失败:', error);
      message.error('更新失败，请重试');
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();

      if (editingId) {
        // Update existing language
        const languageData = {
          lang_id: values.code,
          name: values.name,
          dsc: values.description || '',
          enabled: values.enable
        };

        // 调用API更新语言
        await updateLanguage(editingId, languageData);

        setLanguages(languages.map(item =>
          item.id === editingId ? { ...item, ...values } : item
        ));
        message.success('更新成功');
      } else {
        // Add new language
        const languageData = {
          lang_id: values.code,
          name: values.name,
          dsc: values.description || '',
          enabled: values.enable // 确保启用状态被正确传递
        };

        // 调用API创建语言
        const response = await createLanguage(languageData);

        // 添加到列表中
        setLanguages([...languages, response]);
        message.success('添加成功');
      }
      setIsModalVisible(false);
    } catch (error) {
      console.error('提交表单时出错:', error);
      message.error('操作失败，请重试');
    }
  };

  return (
    <div style={{ padding: '24px', background: '#f0f2f5', minHeight: '100vh' }}>
      <div style={{ maxWidth: '1200px', margin: '0 auto' }}>
        <div style={{
          background: '#fff',
          padding: '24px',
          borderRadius: '2px',
          boxShadow: '0 1px 2px rgba(0, 0, 0, 0.06)'
        }}>
          <div style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: '24px',
            flexWrap: 'wrap',
            gap: '16px'
          }}>
            <h2 style={{ margin: 0 }}>语言管理</h2>
            <Space wrap>
              <Input
                placeholder="搜索语言名称或描述"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                style={{ width: '200px' }}
              />
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                添加语言
              </Button>
              </Space>
          </div>
          <Table
            columns={columns}
            dataSource={filteredLanguages}
            rowKey="id"
            pagination={{
              current: pagination.page,
              pageSize: pagination.pageSize,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
              responsive: true,
              onChange: (page, pageSize) => setPagination({ page, pageSize })
            }}
            scroll={{ x: 'max-content' }}
            style={{ overflowX: 'auto' }}
          />
        </div>
      </div>
      <Modal
        title={editingId ? '编辑语言' : '添加语言'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={520}
      >
        {editingId ? (
          <EditLanguageForm form={form} onFinish={handleModalOk} initialValues={languages.find(lang => lang.id === editingId)!} />
        ) : (
          <AddLanguageForm form={form} onFinish={handleModalOk} />
        )}
      </Modal>
    </div>
  );
};

export default LanguageList;